package com.bluefeather.songlyric;

import android.app.Dialog;
import android.database.Cursor;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SearchToneDlg extends Dialog implements OnClickListener {
	
	public SearchToneDlg(SongLyricActivity activity) {
		super(activity);
		_activity = activity;
		setContentView(R.layout.dlg_search);
		_name = (TextView)findViewById(R.id.search_name);
		Button btn = (Button)findViewById(R.id.b_search);
		btn.setOnClickListener(this);
		setTitle(R.string.search_tone);
	}

	@Override
	public void onClick(View v) {
		String name = _name.getText().toString();
		Cursor c = DB.instance().findToneWord(name);
		if(c.getCount() <= 0) {
			SongLyricApp.instance().showToast(R.string.search_not_found);
		} else if(c.getCount() == 1) {
			int toneId = c.getInt(c.getColumnIndex(DB.TONEWORD._INDEX));
			int toneType = c.getInt(c.getColumnIndex(DB.TONEWORD._TYPE));
			_activity.openTone(toneId, toneType);
		} else {
			int toneId = 0;
			int toneType = 0;
			while(!c.isAfterLast()) {
				String word = c.getString(c.getColumnIndex(DB.TONEWORD._WORDS));
				int pos = word.indexOf(name);
				boolean realMatch = pos >= 0;
				char ch;
				for(int i = 1; i <= 10; ++i)
					if(pos - i >= 0) {
						ch = word.charAt(pos - i);
						if(ch == ']')
							break;
						else if(ch == '[') {
							realMatch = false;
							break;
						}
					}
					else
						break;
				if(realMatch) {
					toneId = c.getInt(c.getColumnIndex(DB.TONEWORD._INDEX));
					toneType = c.getInt(c.getColumnIndex(DB.TONEWORD._TYPE));
					_activity.openTone(toneId, toneType);
				}
				c.moveToNext();
			}
		}
		dismiss();
	}

	private SongLyricActivity	_activity;
	private TextView			_name;
}
